var kscrSelectRepo = "#kscrSelectRepo", kscrTree = "#kscrTree", kscrTreeMenu = "#kscrTreeMenu", kscrDialog = "#kscrDialog";
var kscrFileList = "#kscrFileList", kscrFolderName = "#kscrFolderName", kscrFileTmp = "#kscrFileTmp", kscrFileDialog = "#kscrFileDialog";

$(function() {
	/* 资源库 start */
	$(kscrSelectRepo).combobox({
		onSelect: kscrSelectRepoMethod,
		filter: function(q, row) {
			if ("" == $.trim(q)) return true;
			var opts = $(this).combobox('options');
			return row[opts.textField].indexOf(q) > -1;
		}
	});
	ajaxPost(reqRoute.repositoryList, { pgCt: 1, pgSz: 10000 }, function(resultData) {
		var tmpData = [];
		try {
			if (resultData.status == successCode) {
				$(resultData.data.records).each(function(index, item) {
					tmpData.push({ id: item.id, text: item.repName, type: item.repType });
				});
			}
		} catch(e) {}
		$(kscrSelectRepo).combobox("loadData", tmpData);
	});
	/* 资源库 end */
	
	/* 文件列表 start */
	$(kscrFileList).datagrid({
		columns: [[
			{field:'name', title:'文件名称', halign: 'center', width:150},
			{field:'path', title:'文件路径', halign: 'center', width:300},
			{field:'type', title:'文件类型', halign: 'center', width:100},
			{field:'id', title:'操作', halign: 'center', width:210, formatter:function(value, row, index){
				return '<a class="kscrRename" href="javascript:kscrRename(\''+value+'\')"><i class="fa fa-share fa-lg"></i> 重命名</a>'
					+ '<a class="kscrDel" href="javascript:kscrDel(\''+value+'\',\''+row.name+'\')" style="color:red;"><i class="fa fa-trash fa-lg"></i> 删除</a>'
					+ '<a class="ktask" href="javascript:ktaskAddPage(\''+index+'\')"><i class="fa fa-tasks fa-lg"></i> 新建任务</a>';
			}}
		]],
		loader: function(param, success, error) {
			var repId = $(kscrSelectRepo).combobox("getValue");
			if (!repId && !param.id) {
				success([]);
				return;
			}
			$.get(reqRoute.findScriptById, { repId: repId, dirId: param.id }, function(resultData) {
				var tmpData = [];
				try {
					if (resultData.status == successCode) {
						tmpData = resultData.data;
					}
				} catch(e) {}
				success(tmpData);
			});
		},
		onClickRow: datagridRowUnselect,
		onLoadSuccess: function(resultData) {
			$(".kscrDel").linkbutton({ height: 25, plain: true });
			$(".kscrRename").linkbutton({ height: 25, plain: true });
			$(".ktask").linkbutton({ height: 25, plain: true });
		}
	});
	/* 文件列表 end */
});

function kscrSelectRepoMethod(record) {
	$.messager.progress();
	$(kscrTree).tree({
		loader: function(param, success, error) {
			param.repoId = record.id;
			if (param.id) param.pid = param.id
			delete param.id;
			$.get(reqRoute.findTree, param, function(resultData) {
				$.messager.progress('close');
				var tmpData = [];
				try {
					if (resultData.status == successCode) {
						tmpData = (null == resultData.data ? [] : resultData.data);
						if (!param.id && tmpData.length > 0) {
							$(tmpData).each(function(index, item) {
								if (item.children.length > 0) item.state = 'open';
							});
						}
					}
				} catch(e) {}
				success(tmpData);
			});
		},
		loadFilter: function(resultData, parent) {
			var tmpParam = [];
			$(resultData).each(function(index, item) {
				tmpParam[index] = item;
			});
			return tmpParam;
		},
		onContextMenu: function(e, node) {
			e.preventDefault();
			var delTarget = $(kscrTreeMenu).menu('findItem', "删除").target, 
				cmmTarget = $(kscrTreeMenu).menu('findItem', "重命名").target;
			if ("/" == node.text) {
				$(kscrTreeMenu).menu("hideItem", delTarget);
				$(kscrTreeMenu).menu("hideItem", cmmTarget);
			} else {
				$(kscrTreeMenu).menu("showItem", delTarget);
				$(kscrTreeMenu).menu("showItem", cmmTarget);
			}
			//$(this).tree("select", node.target);
	        $(kscrTreeMenu).menu('show', { left: e.pageX, top: e.pageY }).menu("options").selectNode = node;
		},
		onClick: function(node) {
			$(kscrFileList).datagrid("reload", { id: node.id });
		}
	});
}

function kscrReload() {
	var node = $(kscrTreeMenu).menu("options").selectNode;
	$(kscrTree).tree("reload", node.target);
}

function kscrOpenDialog(flag) {
	var node = $(kscrTreeMenu).menu("options").selectNode;
	var parentNode = $(kscrTree).tree("getParent", node.target);
	var repId = $(kscrSelectRepo).combobox("getValue");
	var tmpUrl = "", resetNode = null;
	
	if ("add" == flag) {
		$(kscrDirPName).textbox("setValue", node.text);
		$(kscrDirName).textbox("clear");
		tmpUrl = reqRoute.dirCreate;
		resetNode = node.target;
	} else {
		$(kscrDirPName).textbox("setValue", parentNode.text);
		$(kscrDirName).textbox("setValue", node.text);
		tmpUrl = reqRoute.dirUpdate;
		resetNode = parentNode.target;
	}
	
	$(kscrDialog).dialog({
		buttons: [{
			text: '保存',
			iconCls: 'icon-ok',
			handler: function() {
				var dirName = $(kscrDirName).textbox("getValue");
				var param = {};
				if ("add" == flag) {
					param = { repId: repId, dirPId: node.id, dirName: dirName };
				} else {
					param = { repId: repId, dirId: node.id, dirName: dirName };
				}
				$(kscrDialog).dialog('close');
				$.messager.progress();
				ajaxPost(tmpUrl, param, function(resultData) {
					try {
						if (resultData.status == successCode) {
							$(kscrTree).tree("reload", resetNode);
						} else {
							$.messager.alert('提示', resultData.message, 'error');
						}
					} catch(e) {}
					$.messager.progress('close');
				});
			}
		},
		{
			text: '取消',
			handler: function() {
				$(kscrDialog).dialog('close');
			}
		}]
	});
	$(kscrDialog).dialog('open');
}

function kscrRemove() {
	var node = $(kscrTreeMenu).menu("options").selectNode;
	var parentNode = $(kscrTree).tree("getParent", node.target);
	var repId = $(kscrSelectRepo).combobox("getValue");
	
	$.messager.confirm('提示', '确定要删除[' + node.text + ']吗？', function(mr) {
	    if (mr) {
	    	$.messager.progress();
	    	$.get(reqRoute.dirDelete, { repId: repId, dirId: node.id }, function(resultData) {
	    		try {
	    			if (resultData.status == successCode) {
		    			$(kscrTree).tree("reload", parentNode.target);
		    		} else {
		    			$.messager.alert('提示', resultData.message, 'error');
		    		}
	    		} catch(e) {}
	    		$.messager.progress('close');
	    	});
	    }
	});
}

function kscrDel(fileId, fileName) {
	var repId = $(kscrSelectRepo).combobox("getValue");
	$.messager.confirm('提示', '确定要删除[' + fileName + ']吗？', function(mr) {
	    if (mr) {
	    	$.get(reqRoute.scriptDel, { repId: repId, fileId: fileId }, function(resultData) {
	    		try {
	    			if (resultData.status == successCode) {
		    			$(kscrFileList).datagrid("reload", { id: $(kscrTree).tree("getSelected").id });
		    		} else {
		    			$.messager.alert("提示", resultData.message, "error");
		    		}
	    		} catch(e) {}
	    	});
	    }
	});
}

function kscrUploadFile() {
	var repId = $(kscrSelectRepo).combobox("getValue"), repData = $(kscrSelectRepo).combobox("getData");
	var treeNode = $(kscrTree).tree("getSelected"), isFlag = false;
	if (!repId) {
		$.messager.alert("提示", "请选择资源库", "info");
		return;
	}
	if (!treeNode) {
		$.messager.alert("提示", "请选择文件夹", "info");
		return;
	}
	$.each(repData, function(index, item){
		if (repId == item.id && item.type == "db") {
			isFlag = true;
			return false;
		}
	});
	if (isFlag) {
		$.messager.alert("提示", "数据库资源库不支持上传", "info");
		return;
	}
	
	$(kscrFolderName).textbox("setValue", treeNode.text);
	$(kscrFileTmp).filebox('clear');
	$(kscrFileDialog).dialog({
		buttons: [{
			text: '保存',
			iconCls: 'icon-ok',
			handler: function() {
				let fileValue = $(kscrFileTmp).filebox('getValue');
				if (fileValue == "") {
			        $.messager.alert('提示', "请选择文件", 'info');
			        return;
			    }
				var files = $(kscrFileTmp).next().find('input[type=file]')[0].files;
				
				var formData = new FormData();
				formData.append("repId", repId);
                formData.append("dirId", treeNode.id);
                formData.append('file', files[0]);
                ajaxFile(reqRoute.scriptUpload, 'POST', formData, function(resultData) {
                	$(kscrFileDialog).dialog('close');
                	if (resultData.status == successCode) {
						$(kscrFileList).datagrid("reload", { id: treeNode.id });
					} else {
						 $.messager.alert('提示', resultData.message, 'error');
					}
                });
			}
		},
		{
			text: '取消',
			handler: function(){
				$(kscrFileDialog).dialog('close');
			}
		}]
	});
	$(kscrFileDialog).dialog('open');
}

function kscrRename(fileId) {
	var repId = $(kscrSelectRepo).combobox("getValue");
	var treeNode = $(kscrTree).tree("getSelected");
	
	$.messager.prompt('重命名', '新文件名称:', function(r){
		if (r){
			$.get(reqRoute.scriptRename, { repId: repId, id: fileId, name: r }, function(resultData) {
				try {
					if (resultData.status == successCode) {
						$(kscrFileList).datagrid("reload", { id: treeNode.id });
					} else {
						$.messager.alert('提示', resultData.message, 'error');
					}
				} catch (e) {}
			});
		}
	});
}

function ktaskAddPage(index) {
	// input 如果存在删除
	let taskData = $(ktaskData).val();
	if (taskData) $(ktaskData).remove();
	// 获取资源库ID
	var repId = $(kscrSelectRepo).combobox("getValue");
	// 获取脚本信息
	var rowData = $(kscrFileList).datagrid("getRows")[index];
	// 设置资源库ID
	rowData.repId = repId;
	
	$("body").append("<input type='hidden' id='"+ktaskData.substr(1)+"' value='"+JSON.stringify(rowData)+"'>");
	$(kcenter).panel({ href: pageRoute.taskAdd });
}